package com.example.experiment1; // 保留实际项目的包名

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

public class ImageViewActivity extends AppCompatActivity {
    private Button buttonPrevious, buttonNext;
    private ImageView imageViewFunny;
    private int[] imageIDArray = {
            R.drawable.funny_1, R.drawable.funny_2,
            R.drawable.funny_3, R.drawable.funny_4,
            R.drawable.funny_5, R.drawable.funny_6
    };

    private int imageIDArrayCurrentIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_image_view);

        // 初始化当前索引为0，显示第一张图片
        imageIDArrayCurrentIndex = 0;

        // 在设置布局后获取控件引用
        buttonPrevious = findViewById(R.id.button_previous);
        buttonNext = findViewById(R.id.button_next); // 修正按钮ID
        imageViewFunny = findViewById(R.id.image_view_funny);

        // 初始显示第一张图片
        imageViewFunny.setImageResource(imageIDArray[imageIDArrayCurrentIndex]);

        // 设置按钮点击监听器
        buttonPrevious.setOnClickListener(new MyButtonClickListener());
        buttonNext.setOnClickListener(new MyButtonClickListener());

        // 处理窗口边距
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }

    private class MyButtonClickListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            // 根据按钮点击更新当前索引，确保索引在有效范围内
            if (view.getId() == R.id.button_next) { // 使用ID判断按钮，更可靠
                imageIDArrayCurrentIndex++;
                if (imageIDArrayCurrentIndex >= imageIDArray.length) {
                    imageIDArrayCurrentIndex = 0; // 循环到第一张
                }
            } else {
                imageIDArrayCurrentIndex--;
                if (imageIDArrayCurrentIndex < 0) {
                    imageIDArrayCurrentIndex = imageIDArray.length - 1; // 循环到最后一张
                }
            }
            // 更新显示的图片
            imageViewFunny.setImageResource(imageIDArray[imageIDArrayCurrentIndex]);
        }
    }
}